package com.fumin.quartz;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fumin.common.CalV1;
import com.fumin.pojo.*;
import com.fumin.service.*;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时更新投资记录
 * 
 * @author Lingo
 * 
 */
@Component
public class DataSync {

	private static Logger logger = Logger.getLogger(DataSync.class);

	@Resource
	InvestmentRecordService investmentRecordService;
	@Resource
	ProjectsService projectsService;
	@Resource
	CapitalService capitalService;
	@Resource
	UserService userService;
	@Resource
	CoinCountService coinCountService;


	@Transactional
	@Scheduled(cron = "0 00 00 * * ?")
	public void autoStatisticWxInfo() {

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<CoinCount> coinCountList = new LinkedList<>();
		List<Projects> projectsList = projectsService.selectByStatus(0);
		List<InvestmentRecord> waitToInsert= new LinkedList<>();
		String url = "http://api.etherscan.io/api?module=account&action=txlist&" +
				"address=%s" +
				"&startblock=0&endblock=99999999&sort=desc&" +
				"apikey=%s";
		for (Projects projects:projectsList) {
			String tempUrl  = String.format(url,projects.getProject_wallet(),"H6T8WITXFCYG189UEFV2FTNAGWZQIFWHQW");
			HttpResponse<String> response  = null;
			try {
				response = Unirest.get(tempUrl)
						.header("cache-control", "no-cache")
						.header("postman-token", "01e8236c-7f07-2b64-833e-0a5403afd5d9")
						.asString();
			} catch (UnirestException e) {
				logger.error(e.getMessage());
			}
			String body = response.getBody();
			JSONObject resuelt = JSON.parseObject(body);
			JSONArray ethResutlt = resuelt.getJSONArray("result");
			List<EthTransaction> ethTransactionList =  JSONObject.parseArray(ethResutlt.toString(), EthTransaction.class);
			List<InvestmentRecord> investmentRecordList =  investmentRecordService.selectAllByProjectPk(projects.getPk());
			//创建散列缓存 数据中的投资记录 交易hash - - - -交易记录
			Map<String,InvestmentRecord> recordMap = new HashMap<>();
			for (InvestmentRecord record:investmentRecordList) {
				String txHash = record.getTransaction_hash().toUpperCase();
				recordMap.put(txHash,record);
			}
			BigDecimal projectAmount = new BigDecimal(projects.getTotal_amount());

			for (EthTransaction ethTransaction:ethTransactionList) {
				InvestmentRecord  investmentRecord = recordMap.get(ethTransaction.getHash().toUpperCase());
				// 如果项目交易hash在现有的数据库中不存在，检查检索该交易来源是否是已知用户
				if (investmentRecord==null){
					String addr = ethTransaction.getFrom();
					Capital capital = capitalService.selectByAcountAddr(addr);
					// 如果数据库中无此记录，说明用户未添加正确的钱包地址，该投资记录暂时抛弃
					// 当数据库中存在此记录时，说明用户已正确填写钱包地址，写入该投资记录
					if (capital!=null){
						InvestmentRecord toInsert = new InvestmentRecord();
						toInsert.setUser_id(capital.getUser_id());
						toInsert.setProject_id(projects.getPk());
						toInsert.setProject_name(projects.getProject_name());
						BigDecimal txBigValue = new BigDecimal(ethTransaction.getValue());

						projectAmount.add(txBigValue.divide(new BigDecimal("1000000000000000000")));

						toInsert.setAmount(ethTransaction.getValue());
						toInsert.setUnit("ETH");
						toInsert.setStatus(1);
						toInsert.setTransaction_hash(ethTransaction.getHash());
						String completeTimeStamp = ethTransaction.getTimeStamp()+"000";
						toInsert.setTime(simpleDateFormat.format(new Date(Long.getLong(completeTimeStamp))));
						waitToInsert.add(toInsert);
						CalV1 calV1 = new CalV1();
						coinCountList.addAll(calV1.countCoinByInventRecords(toInsert,projects,userService));
					}
				}
			}
			projects.setTotal_amount(projectAmount.toString());
		}
		investmentRecordService.insertList(waitToInsert);
		projectsService.updateAmountByMany(projectsList);
		coinCountService.insertMany(coinCountList);
	}
}
